<template>
  <div class="product-management-container">
    <div class="header">
      <h1>商品管理</h1>
      <el-button type="primary" @click="handleAddProduct">
        <el-icon><Plus /></el-icon>
        添加商品
      </el-button>
    </div>
    
    <!-- 搜索和筛选 -->
    <div class="search-filter">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索商品名称或ID"
        style="width: 300px; margin-right: 10px"
        @keyup.enter="fetchProducts"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      
      <el-select v-model="categoryFilter" placeholder="选择分类" style="width: 150px; margin-right: 10px" @change="fetchProducts">
        <el-option label="全部分类" value="" />
        <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
      </el-select>
      
      <el-select v-model="statusFilter" placeholder="商品状态" style="width: 120px; margin-right: 10px" @change="fetchProducts">
        <el-option label="全部状态" value="" />
        <el-option label="上架" value="1" />
        <el-option label="下架" value="0" />
      </el-select>
      
      <el-button type="default" @click="resetFilters">重置筛选</el-button>
    </div>
    
    <!-- 商品列表 -->
    <div class="product-list">
      <el-table :data="products" style="width: 100%" border>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="商品ID" width="100" fixed="left" />
        <el-table-column prop="name" label="商品名称" min-width="200">
          <template #default="scope">
            <div class="product-info">
              <img :src="scope.row.image" alt="{{ scope.row.name }}" class="product-thumbnail" />
              <span>{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">{{ getCategoryName(scope.row.categoryId) }}</template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">¥{{ scope.row.price.toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100" />
        <el-table-column prop="sales" label="销量" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row.status" @change="toggleProductStatus(scope.row.id, $event)" />
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">{{ formatDate(scope.row.createdAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleEditProduct(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleDeleteProduct(scope.row.id)" danger>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 添加/编辑商品弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑商品' : '添加商品'" width="600px">
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入商品名称" />
        </el-form-item>
        
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="formData.categoryId" placeholder="请选择商品分类">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="formData.price" :min="0" :step="0.01" placeholder="请输入商品价格" />
        </el-form-item>
        
        <el-form-item label="商品库存" prop="stock">
          <el-input-number v-model="formData.stock" :min="0" placeholder="请输入商品库存" />
        </el-form-item>
        
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="formData.description" type="textarea" placeholder="请输入商品描述" />
        </el-form-item>
        
        <el-form-item label="商品图片" prop="image">
          <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            action="#"
            :show-file-list="true"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :auto-upload="false"
            list-type="picture"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">只能上传jpg/png文件，且不超过2MB</div>
            </template>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="商品状态" prop="status">
          <el-switch v-model="formData.status" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus } from '@element-plus/icons-vue';
import type { FormInstance, FormRules } from 'element-plus';
import type { UploadFile, UploadProps } from 'element-plus';

// 商品接口定义
interface Product {
  id: number;
  name: string;
  categoryId: number;
  category: string;
  price: number;
  stock: number;
  sales: number;
  description: string;
  image: string;
  status: boolean;
  createdAt: string;
  updatedAt: string;
}

// 分类接口定义
interface Category {
  id: number;
  name: string;
}

// 响应式数据
const products = ref<Product[]>([]);
const categories = ref<Category[]>([
  { id: 1, name: '电子产品' },
  { id: 2, name: '家居用品' },
  { id: 3, name: '服装鞋帽' },
  { id: 4, name: '食品饮料' },
  { id: 5, name: '图书文具' }
]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchKeyword = ref('');
const categoryFilter = ref('');
const statusFilter = ref('');

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();
const fileList = ref<UploadFile[]>([]);

// 表单数据
const formData = reactive({
  id: 0,
  name: '',
  categoryId: 0,
  price: 0,
  stock: 0,
  description: '',
  image: '',
  status: true
});

// 表单验证规则
const formRules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '商品名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '商品价格必须大于或等于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' },
    { type: 'number', min: 0, message: '商品库存必须大于或等于0', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传商品图片', trigger: 'change' }
  ]
});

// 获取商品列表
const fetchProducts = async () => {
  // 这里应该调用API获取实际数据
  // 目前使用模拟数据
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 模拟数据
    const mockProducts: Product[] = [
      { id: 1, name: '智能手机 Pro', categoryId: 1, category: '电子产品', price: 5999.00, stock: 100, sales: 1500, description: '高性能智能手机，搭载最新处理器', image: 'https://picsum.photos/id/1/80/80', status: true, createdAt: '2024-01-01T10:00:00Z', updatedAt: '2024-01-05T14:30:00Z' },
      { id: 2, name: '无线蓝牙耳机', categoryId: 1, category: '电子产品', price: 899.00, stock: 200, sales: 3200, description: '高音质无线蓝牙耳机，降噪功能', image: 'https://picsum.photos/id/2/80/80', status: true, createdAt: '2024-01-02T11:00:00Z', updatedAt: '2024-01-06T09:15:00Z' },
      { id: 3, name: '时尚连衣裙', categoryId: 3, category: '服装鞋帽', price: 299.00, stock: 150, sales: 850, description: '春季新款时尚连衣裙，舒适透气', image: 'https://picsum.photos/id/3/80/80', status: true, createdAt: '2024-01-03T09:30:00Z', updatedAt: '2024-01-07T16:45:00Z' },
      { id: 4, name: '有机蔬菜礼盒', categoryId: 4, category: '食品饮料', price: 199.00, stock: 50, sales: 420, description: '纯天然有机蔬菜，健康营养', image: 'https://picsum.photos/id/4/80/80', status: false, createdAt: '2024-01-04T14:20:00Z', updatedAt: '2024-01-08T11:20:00Z' },
      { id: 5, name: '科幻小说精选', categoryId: 5, category: '图书文具', price: 128.00, stock: 80, sales: 630, description: '经典科幻小说合集，共5本', image: 'https://picsum.photos/id/5/80/80', status: true, createdAt: '2024-01-05T16:10:00Z', updatedAt: '2024-01-09T13:50:00Z' }
    ];
    
    // 模拟搜索和筛选
    let filteredProducts = [...mockProducts];
    
    if (searchKeyword.value) {
      const keyword = searchKeyword.value.toLowerCase();
      filteredProducts = filteredProducts.filter(product => 
        product.name.toLowerCase().includes(keyword) || product.id.toString().includes(keyword)
      );
    }
    
    if (categoryFilter.value) {
      filteredProducts = filteredProducts.filter(product => 
        product.categoryId === Number(categoryFilter.value)
      );
    }
    
    if (statusFilter.value !== '') {
      filteredProducts = filteredProducts.filter(product => 
        product.status === (statusFilter.value === '1')
      );
    }
    
    // 模拟分页
    total.value = filteredProducts.length;
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const endIndex = startIndex + pageSize.value;
    products.value = filteredProducts.slice(startIndex, endIndex);
    
  } catch (error) {
    ElMessage.error('获取商品列表失败');
    console.error('获取商品列表失败:', error);
  }
};

// 获取分类名称
const getCategoryName = (categoryId: number) => {
  const category = categories.value.find(cat => cat.id === categoryId);
  return category ? category.name : '未知分类';
};

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).format(date);
};

// 重置筛选条件
const resetFilters = () => {
  searchKeyword.value = '';
  categoryFilter.value = '';
  statusFilter.value = '';
  currentPage.value = 1;
  fetchProducts();
};

// 切换商品状态
const toggleProductStatus = async (productId: number, status: boolean) => {
  try {
    // 这里应该调用API更新商品状态
    // 目前模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300));
    
    ElMessage.success(`商品${status ? '上架' : '下架'}成功`);
    // 不需要重新获取列表，因为状态已经在前端更新了
  } catch (error) {
    ElMessage.error('更新商品状态失败');
    console.error('更新商品状态失败:', error);
    // 恢复原来的状态
    const product = products.value.find(p => p.id === productId);
    if (product) {
      product.status = !status;
    }
  }
};

// 处理添加商品
const handleAddProduct = () => {
  isEdit.value = false;
  // 重置表单
  Object.assign(formData, {
    id: 0,
    name: '',
    categoryId: 0,
    price: 0,
    stock: 0,
    description: '',
    image: '',
    status: true
  });
  fileList.value = [];
  dialogVisible.value = true;
};

// 处理编辑商品
const handleEditProduct = (product: Product) => {
  isEdit.value = true;
  // 填充表单数据
  Object.assign(formData, product);
  // 设置文件列表
  fileList.value = product.image ? [{ url: product.image }] as UploadFile[] : [];
  dialogVisible.value = true;
};

// 处理删除商品
const handleDeleteProduct = async (productId: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个商品吗？删除后将无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    // 这里应该调用API删除商品
    // 目前模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    
    ElMessage.success('商品删除成功');
    fetchProducts(); // 重新获取商品列表
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除商品失败');
      console.error('删除商品失败:', error);
    }
  }
};

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    // 这里应该调用API保存商品
    // 目前模拟API调用
    await new Promise(resolve => setTimeout(resolve, 800));
    
    ElMessage.success(isEdit.value ? '商品编辑成功' : '商品添加成功');
    dialogVisible.value = false;
    fetchProducts(); // 重新获取商品列表
  } catch (error) {
    ElMessage.error(isEdit.value ? '商品编辑失败' : '商品添加失败');
    console.error('表单验证失败:', error);
  }
};

// 上传文件相关方法
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log('preview', uploadFile);
};

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log('remove', uploadFile, uploadFiles);
  formData.image = '';
  return true;
};

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 模拟上传成功，设置图片URL
  formData.image = `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/80/80`;
  return false; // 阻止自动上传
};

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  fetchProducts();
};

const handleCurrentChange = (current: number) => {
  currentPage.value = current;
  fetchProducts();
};

// 组件挂载时获取商品列表
onMounted(() => {
  fetchProducts();
});
</script>

<style scoped>
.product-management-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h1 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.search-filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.product-list {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-thumbnail {
  width: 40px;
  height: 40px;
  object-fit: cover;
  margin-right: 10px;
  border-radius: 4px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-management-container {
    padding: 10px;
  }
  
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-filter {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .search-filter .el-input,
  .search-filter .el-select {
    width: 100% !important;
    margin-right: 0 !important;
  }
  
  .pagination {
    justify-content: center;
  }
}

@media (max-width: 1200px) {
  .el-table .el-table__fixed-right {
    display: none;
  }
  
  .el-table .el-table__fixed-left {
    display: none;
  }
}
</style>